var express = require('express');
var router = express.Router();
const { saveArticle, getArticleList, getArticle, setRecentReadingTime, getRecentReadingList, editArticle, deleteArticle } = require('../serve/article');
const { v4: uuidv4 } = require('uuid');
const dayjs = require('dayjs');
const { authenticateToken } = require('../plugin/jwt');

router.post('/saveArticle', authenticateToken, async (req, res, next) => {
  try {
    const id = uuidv4();
    const createTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    const data = saveArticle({
      id,
      createTime,
      editTime: createTime,
      recentReadingTime: Date.now(),
      ...req.body,
      isDelete: 1,
    })
    res.send(data);
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: 'An error occurred while fetching data.' });
  }
})

router.post('/editArticle', authenticateToken, async (req, res, next) => {
  try {

    const { id } = req.body;
    if (!id) {
      res.send({
        code: -1,
        msg: '请传入id'
      })
    }
    const editTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
    const data = editArticle({
      editTime,
      recentReadingTime: Date.now(),
      ...req.body
    })
    res.send(data);
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: 'An error occurred while fetching data.' });
  }
})

router.post('/getArticleList', async (req, res, next) => {
  try {
    console.log(req.body);
    const data = await getArticleList(req.body);
    res.send(data);
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: 'An error occurred while fetching data.' });
  }
})

router.post('/getArticle', async (req, res, next) => {
  try {
    const data = await getArticle(req.body.id);
    res.send(data);
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: 'An error occurred while fetching data.' });
  }
})

router.post('/setRecentReading', async (req, res, next) => {
  try {
    console.log(req.body);
    let { id, recentReadingTime } = req.body;
    if (id && recentReadingTime) {
      const data = await setRecentReadingTime(id, recentReadingTime);
      res.send(data);
    }
  } catch (err) {
    console.log(error);
    res.status(500).json({ error: 'An error occurred while fetching data.' });
  }
})
router.get('/recentReadingList', async (req, res, next) => {
  try {
    const data = await getRecentReadingList();
    res.send(data);
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: 'An error occurred while fetching data.' });
  }
})

router.post('/deleteArticle', authenticateToken, async (req, res, next) => {
  try {
    const { id } = req.body;
    if (!id) {
      res.send({
        code: -1,
        msg: '请传入id'
      })
    }
    const data = await deleteArticle(id);
    res.send(data);
  } catch (error) {
    console.log(error);
    res.status(500).json({ error: 'An error occurred while fetching data.' });
  }
})

module.exports = router;